const electron = require('electron');
const app = electron.app;

const globalShortcut = electron.globalShortcut;
// const dialog = electron.dialog;

const browser = electron.BrowserWindow;
const Menu = electron.Menu;
const Tray = electron.Tray;
const path = require('path');
const url = require('url');
const trayIcon = path.join(__dirname, 'portal');



// 检测是否存在已经打开的窗口

let win = null

const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
	app.quit()
} else {
	app.on('second-instance', (event, commandLine, workingDirectory) => {
		// 当运行第二个实例时,将会聚焦到myWindow这个窗口
		if (win) {
			if (win.isMinimized()) win.restore()
			win.focus();
		}
	})
	// 创建 myWindow, 加载应用的其余部分, etc...
	app.on('ready', () => {
		createWindow();
	})
};

let tray = null;


function createWindow() {

	win = new browser({
		width: 1280,
		height: 800,
		minWidth: 1280,
		minHeight: 800,
		icon: path.join(trayIcon, 'app.png'),
		title: 'Requester',
		webPreferences: {
			nodeIntegration: true,
		}
	});
	win.loadURL(url.format({
		pathname: path.join(__dirname, 'index.html'),
		protocol: 'file:',
		slashes: true,
		skipTaskbar: false,
	}));

	// globalShortcut.register('CommandOrControl+S', function () {
	// 	var isFocus = win.isFocused();
	// 	if (isFocus) {
	// 		win.webContents.send('Save-Content', 'main-process-messages show');
	// 	};
	// });
	// globalShortcut.register('Alt+R', function () {
	// 	var isFocus = win.isFocused();
	// 	if (isFocus) {
	// 		win.hide();
	// 	} else {
	// 		win.show();
	// 		win.focus();
	// 	};
	// });

	if (process.platform !== 'darwin') {
		const trayMenuTemplate = [{
			label: 'exit',
			click: function () {
				app.quit();
			}
		}];
		tray = new Tray(path.join(trayIcon, 'appicon.png'));
		const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
		tray.setToolTip('Requester');
		tray.setContextMenu(contextMenu);
		win.on('close', function (e) {
			e.preventDefault();
			win.hide();
		});
		tray.on("click", function () {
			var isFocus = win.isFocused();
			if (isFocus) {
				win.hide();
			} else {
				win.show();
				win.focus();
			};
		});
	};

};









app.on('activate', function () {
	if (win === null) {
		createWindow()
	} else {
		var isFocus = win.isFocused();
		if (isFocus) {
			win.hide();
		} else {
			win.show();
			win.focus();
		};
	}
});

// app.on('quit', function (event) {
// 	event.preventDefault();
// 	// app.quit();
// });

// app.on('window-all-closed', function (event) {
// 	event.preventDefault();
// 	//...
// 	// On macOS it is common for applications and their menu bar
// 	// to stay active until the user quits explicitly with Cmd + Q
// 	if (process.platform !== 'darwin') {
// 		app.quit()
// 	}
// });
